package MTRequest;

import java.sql.ResultSet;

import MTProxyServer.MTConstant;
import MTProxyServer.MessageCentre;
import SQLManager.SQLManager;

public class MTServerSynDataFromLocalDB extends MTRequest{
	
	private int mCurIndex = 0;
	
	public MTServerSynDataFromLocalDB( MessageCentre aMSGCenter )
	{
		super( aMSGCenter );
	}
	
	protected void UpdateRequestState( int aPeerState )
	{
		if( MTConstant.MT_REQ_CSYN_DFLDB_SEND_PRODUCT_LAST == aPeerState ){
			++mCurIndex;
			this.mRequestState = MTConstant.MT_REQ_SSYN_DFLDB_UPDATE_PRODUCT_LAST;
		}
		else if( MTConstant.MT_REQ_CSYN_DFLDB_SYNCHRONIZE_REQUEST == aPeerState ){
			this.mRequestState = MTConstant.MT_REQ_SSYN_DFLDB_READY;
		}
		else if( MTConstant.MT_REQ_CSYN_DFLDB_SEND_PRODUCT == aPeerState ){
			++mCurIndex;
			this.mRequestState = MTConstant.MT_REQ_SSYN_DFLDB_UPDATE_PRODUCT;
		}
	}
	
	protected void ProcessReqest( int aPeerState, String peerRawData )
	{
		switch( aPeerState ){
			case MTConstant.MT_REQ_CSYN_DFLDB_SYNCHRONIZE_REQUEST:{
				this.mReceivedFromPeerRawData.add( peerRawData );
				System.out.println( " UserID " + peerRawData );
				break;
			}
			case MTConstant.MT_REQ_CSYN_DFLDB_SEND_PRODUCT:
			case MTConstant.MT_REQ_CSYN_DFLDB_SEND_PRODUCT_LAST:{
				
				this.mReceivedFromPeerRawData.add( peerRawData );
				
				String [] updateItemsGet = peerRawData.split( "" + MTConstant.MT_REQ_RAW_DATA_SEPARATER );
				String[] updateItems = new String[8];
				
				for(int i=0; i<updateItemsGet.length; i++)
					updateItems[i] = updateItemsGet[i];
				
				int productID = 0;
				String updateType = updateItems[0];
				String eventID = null;
				String master = null;
				String content = "";
				switch( Integer.valueOf( updateItems[0] ) ){
					case MTConstant.MT_ID_UPT_CREATE_PRODUCT:{
						productID = HandleCreateProduct( updateItems );
						eventID = updateItems[1];
						master = updateItems[2];
						content = "" + productID;
						this.mSendingToPeerRawData.add( "" + productID );
						break;
					}
					case MTConstant.MT_ID_UPT_DELETE_PRODUCT:{
						HandleDeleteProduct( updateItems );
						break;
					}
					case MTConstant.MT_ID_UPT_EDIT_PRODUCT:{
						HandleEditProduct( updateItems );
						break;
					}
					case MTConstant.MT_ID_UPT_CREATE_TABLE:{
						eventID = HandleCreateEventTable( updateItems );
						master = updateItems[1];
						this.mSendingToPeerRawData.add( eventID );
						break;
					}
					case MTConstant.MT_ID_UPT_DELETE_TABLE:{
						HandleDeleteEventTable();
						break;
					}
					case MTConstant.MT_ID_UPT_EDIT_TABLE:{
						HandleEditEventTable();
						break;
					}
				}
				
				HandleSynchronizeWithOthers( eventID, master, content , updateType );
				// Assign one Event ID
				//
				// if( result != null )
				// update the event Info on Server side;
				// update the Update Table, Synchronize Table
				
				break;
			}
		}
	}
	
	public void SendRequest()
	{
		String request = "" + MTConstant.MT_REQID_SYNCHRONIZE_DATA_FROM_LOCAL_DB + MTConstant.MT_REQ_ITEM_SEPARATER + 
		this.mRequestState + MTConstant.MT_REQ_ITEM_SEPARATER;
		switch( this.mRequestState ){
			case MTConstant.MT_REQ_SSYN_DFLDB_READY:{
				request += " ";
				break;
			}
			case MTConstant.MT_REQ_SSYN_DFLDB_UPDATE_PRODUCT:
			case MTConstant.MT_REQ_SSYN_DFLDB_UPDATE_PRODUCT_LAST:{
				request += this.mSendingToPeerRawData.get( mCurIndex - 1);
				break;
			}
		}
		this.SendMSG(request);		
		
		if( MTConstant.MT_REQ_SSYN_DFLDB_UPDATE_PRODUCT_LAST == this.mRequestState ){
			this.Finish();
		}
	}
	
	private int HandleCreateProduct( String [] updateItems )
	{
		int productID = 0;
		String requestUserID = this.mReceivedFromPeerRawData.get( 0 );
		
		// Update Type ID, EventID, Master, ProductID ( not for Create Product ), Owner, 
		//Product Name, Description, Price, Quality, Image
		
		System.out.println("--->HandleCreateProduct()");
		System.out.println("Update Type:" + updateItems[0] );
		System.out.println("EventID:" + updateItems[1] );
		System.out.println("Master:" + updateItems[2] );
		System.out.println("Owner:" + requestUserID );
		System.out.println("ProductName:" + updateItems[3] );
		System.out.println("Description:" + updateItems[4] );
		System.out.println("Price:" + updateItems[5] );
		System.out.println("Quality:" + updateItems[6] );
		System.out.println("Image:" + updateItems[7] );
		
		String query = String.format(
				"INSERT INTO " + MTConstant.MT_SQL_DB + ".ProductList_%s ( Owner, ProductName, Description, Price, Quality, Image ) " +
				"VALUES ( %s, '%s', '%s', %s, %s, '%s' )", 
				updateItems[1],
				requestUserID,
				updateItems[3],
				updateItems[4],
				updateItems[5],
				updateItems[6], 
				updateItems[7] );
		
		SQLManager sqlManager = SQLManager.GetInstance();
		try{
			sqlManager.ConnectSQL( );
			sqlManager.UpdateTable( query );
			
			query = "SELECT LAST_INSERT_ID()";
			ResultSet rs = sqlManager.Query( query, "");
			
			if( rs.next() ){
				productID = rs.getInt( 1 );
			}
			
			sqlManager.Close();
		}
		catch( Exception e ){
			e.printStackTrace();
		}
		System.out.println("<---HandleCreateProduct()");
		
		return productID;
	}
	
	private void HandleEditProduct( String [] updateItems )
	{
		
	}
	
	private void HandleDeleteProduct( String [] updateItems )
	{
		
	}
	
	//private void HandleSynchronizeWithOthers( int aProductID, String [] aUpdateItems, String aEventID, String aMaster, String aConent, String aUpdateType )
	private void HandleSynchronizeWithOthers( String aEventID, String aMaster, String aContent, String aUpdateType )
	
	{
		String requestUserID = this.mReceivedFromPeerRawData.get( 0 );
		
		// Update Type ID, EventID, Master, ProductID ( not for Create Product ), Owner, 
		//Product Name, Description, Price, Quality, Image
		
		System.out.println("--->HandleSynchronizeWithOthers()");
		System.out.println( "requestUserID" + requestUserID);
		System.out.println( "aEventID" + aEventID);
		System.out.println( "aMaster" + aMaster);
		System.out.println( "aContent" + aContent);
		System.out.println( "aUpdateType" + aUpdateType);
//		System.out.println("Update Type:" + updateItems[0] );
//		System.out.println("EventID:" + updateItems[1] );
//		System.out.println("Master:" + updateItems[2] );
//		System.out.println("Owner:" + requestUserID );
//		System.out.println("ProductName:" + updateItems[3] );
//		System.out.println("Description:" + updateItems[4] );
//		System.out.println("Price:" + updateItems[5] );
//		System.out.println("Quality:" + updateItems[6] );
//		System.out.println("Image:" + updateItems[7] );
		
		String query = String.format(
				"SELECT ContactMember FROM " + MTConstant.MT_SQL_DB + ".EventTable WHERE EventID = %s", 
				aEventID );
		
		SQLManager sqlManager = SQLManager.GetInstance();
		try{
			sqlManager.ConnectSQL( );
			ResultSet rs = sqlManager.Query( query , "" );
			//String eventMaster = null;
			String contactMemberStr = null;
			if( rs.next() ){
				//eventMaster = rs.getString( 1 );
				contactMemberStr = rs.getString( 1 );
				
				//System.out.println( "eventMaster: " + eventMaster );
				System.out.println( "contactMemberStr: " + contactMemberStr );
			}
			
			String [] contactMember = contactMemberStr.split( " " );
			
			if(  Integer.parseInt( aUpdateType ) != MTConstant.MT_ID_UPT_CREATE_TABLE ){
				for( int i = 0 ; i < contactMember.length; ++i ){
					if( !contactMember[i].matches( requestUserID ) ){
						// Update User's UpdateTable except the user who request
						String userDB = "User_" + contactMember[i];
						
							query = String.format(
									"INSERT INTO " + MTConstant.MT_SQL_DB + ".%s_UpdateTable ( EventID, Master, Content, IsFinished, UpdateType, TimeCreated ) VALUES ( %s, %s, '%s', %b, %s, NOW() )", 
									userDB,
									aEventID,
									aMaster,
									aContent,
									false,
									aUpdateType );
							
							System.out.println( "Query:" + query );
	//					}
						sqlManager.UpdateTable( query );
						
						// Update Event's Synchronize Table
						query = String.format(
								"UPDATE " + MTConstant.MT_SQL_DB + ".SynchronizeTable_%s SET IsUpdated = false, UpdateCount = UpdateCount + 1 WHERE UserID = %s"
								, aEventID
								, contactMember[i] );
						sqlManager.UpdateTable( query );
						
					}
				}
			}
			
			sqlManager.Close();
		}
		catch( Exception e ){
			e.printStackTrace();
		}
		System.out.println("<---HandleSynchronizeWithOthers()");
	}
	
	
	// Code Repeat as Create Event
	private String HandleCreateEventTable( String [] eventInfoItem )
	{
		System.out.println("--->HandleCreateEventTable()");
		String eventID = "";
		
		// Master, Title, Contact Member, Location
		//String [] eventInfoItem = aEventInfo.split( "" + MTConstant.MT_REQ_RAW_DATA_SEPARATER );
		
		SQLManager sqlManager = SQLManager.GetInstance();
		
		try{
			sqlManager.ConnectSQL(  );
			
			String query = String.format(
					"INSERT INTO " + MTConstant.MT_SQL_DB + ".EventTable ( Master, Title, ContactMember, Location ) " +
					"VALUES ( %s, %s, %s, %s )", 
					eventInfoItem[1],
					eventInfoItem[2],
					eventInfoItem[3],
					eventInfoItem[4] );
			
			sqlManager.UpdateTable( query );
			
			query = "SELECT LAST_INSERT_ID()";
			ResultSet rs = sqlManager.Query( query, "" );
			
			if( rs.next() ){
				eventID = rs.getString( 1 );
			}
			
			// Create Event's Synchonize Table and ProductList
			query = String.format(  
					"CREATE TABLE " + MTConstant.MT_SQL_DB + ".SynchronizeTable_%s ( " +
					"UserID INT NOT NULL ," +
					"IsUpdated TINYINT(1) ZEROFILL NULL," +
					"UpdateCount INT NULL," +
					"PRIMARY KEY ( UserID ) )"
					, eventID );
			sqlManager.UpdateTable( query );
			
			query = String.format(
				"CREATE  TABLE " + MTConstant.MT_SQL_DB + ".ProductList_%s (" +
					  "ProductID INT NOT NULL AUTO_INCREMENT ," +
					  "Owner INT NULL ," +
					  "ProductName VARCHAR(45) NULL ," +
					  "Description VARCHAR(255) NULL ," +
					  "Price FLOAT NULL ," +
					  "Quality FLOAT NULL ," +
					  "Image VARCHAR(45) NULL ," +
					  "PRIMARY KEY (ProductID) ," +
					  "UNIQUE INDEX ProductID_UNIQUE (ProductID ASC) )"
					  , eventID );
			sqlManager.UpdateTable( query );
			
			String contactMemberStr = eventInfoItem[ 3 ].substring( 1, eventInfoItem[ 3 ].length() - 1 );
			String [] contactMembers = contactMemberStr.split( " " );
			
			for( int i = 0 ; i < contactMembers.length; ++i ){
				System.out.println( "Contact Member " + i + " " + contactMembers[i] );
			}
			// Update User's Update Table
			
			for( int i = 0; i < contactMembers.length; ++i ){
				String userDB = "User_" + contactMembers[i];
				System.out.println( "UerDB:" + userDB );
				if( !eventInfoItem[1].matches( contactMembers[i] ) ){
					query = String.format(
							"INSERT INTO " + MTConstant.MT_SQL_DB+ ".%s_UpdateTable ( EventID, Master, IsFinished, UpdateType, TimeCreated ) VALUES ( %s, %s, %b, %d, NOW() )", 
							userDB,
							eventID,
							contactMembers[0],
							false,
							MTConstant.MT_ID_UPT_CREATE_TABLE );
					sqlManager.UpdateTable( query );
				}
			}
			
			// Update SynchroizeTable
			System.out.println(" Update SynchroizeTable");
			for( int i = 0 ; i < contactMembers.length ; ++i ){
				
				boolean isUpdated = true;
				int count = 0;
				
				// If not a matser
				if( !eventInfoItem[1].matches( contactMembers[i] ) ){
					isUpdated = false;
					count = 1;
				}
				query = String.format(
						"INSERT INTO " + MTConstant.MT_SQL_DB + ".SynchronizeTable_%s ( UserID, IsUpdated, UpdateCount ) VALUES ( %s, %b, %d )", 
						eventID,
						contactMembers[i],
						isUpdated,
						count );
				sqlManager.UpdateTable( query );
			}
			
			sqlManager.Close();
		}
		catch( Exception e ){
			e.printStackTrace();
		}
		System.out.println("<---HandleCreateEventTable()");
		
		return eventID;
	}
	
	private void HandleEditEventTable()
	{
	
	}
	
	private void HandleDeleteEventTable()
	{
		
	}

}
